#include "stm32f10x.h"                  // Device header

void Motor_Init(void)
{
  //初始化外设时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//IO口时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);//定时器时钟
  
  //初始化IO口
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;//复用推挽输出
	GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2;
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructure);//PWM输出IO配置完成
	
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10|GPIO_Pin_11;
	GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructure);//方向控制IO口配置完成
	
  //初始化定时器
	TIM_InternalClockConfig(TIM2);//定时器时钟源为RCC内部时钟
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_Period=100-1;//ARR
	TIM_TimeBaseInitStructure.TIM_Prescaler=100-1;//PSC
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter=0x00;
    TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);//时基单元配置完成

	
	//配置输出比较单元
	TIM_OCInitTypeDef TIM_OCInitStructure;
	TIM_OCStructInit(&TIM_OCInitStructure);
	TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
	TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
	TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_Pulse=0;//CCR
	TIM_OC3Init(TIM2,&TIM_OCInitStructure);//输出比较通道配置完成
	
    TIM_Cmd(TIM2,ENABLE);//使能定时器
	
}

void set_frequency(uint32_t freq)
{
   uint32_t PSC=720000/freq-1;
   TIM_PrescalerConfig(TIM2,PSC,TIM_PSCReloadMode_Immediate);
}

void Set_Speed(int16_t speed)
{
   if(speed>0)
   {
	TIM_SetCompare3(TIM2,speed);
    GPIO_SetBits(GPIOA,GPIO_Pin_10);
    GPIO_ResetBits(GPIOA,GPIO_Pin_11);
   }
   else if(speed<=0)
   {
    TIM_SetCompare3(TIM2,-speed);
    GPIO_SetBits(GPIOA,GPIO_Pin_11);
    GPIO_ResetBits(GPIOA,GPIO_Pin_10);
   }
}
